﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using HQPad.Models;
using HQPad.DAL;
using HQPad.Services;

namespace HQPad.Helpers
{
    /// <summary>
    /// Functionality to help manipulate the forms authentication data.
    /// </summary>
    public class AuthenticationHelper
    {
        public static string GetCurrentSessionId(HttpRequestBase request)
        {
            string cookie = request.Cookies[FormsAuthentication.FormsCookieName].Value;
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie);

            return ticket.UserData;
        }

        public static void SetAuthTicket (HttpResponseBase response, string userName, bool rememberMe)
        {
            string sessionId = Guid.NewGuid().ToString().Replace("{", "").Replace("}", "");

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                userName,
                DateTime.Now,
                DateTime.Now.AddMinutes(300),
                rememberMe,
                sessionId, // set scratch pad session id (guid).
                FormsAuthentication.FormsCookiePath);

            // Encrypt the ticket.
            string encTicket = FormsAuthentication.Encrypt(ticket);

            // Create the cookie.
            response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

            IUnitOfWork context = new CharacterContext();
            ICharacterService characterService = new CharacterService(context);

            characterService.TidyScratchPad(userName, sessionId);
            context.Save();
        }

        public static string GetCurrentUserName(HttpContextBase context)
        {
            return context.User.Identity.Name;
        }

        public static void Logout()
        {
            FormsAuthentication.SignOut();
        }

        public static bool CheckPasswordForNonAlpha(string password)
        {
            string pattern;
            pattern = "[^a-zA-Z0-9\n\r\t ]";
            Regex oReg = new Regex(pattern, RegexOptions.IgnoreCase);
            return oReg.IsMatch(password);
        }
    }
}